'use strict';

let fs = require('fs');
let path = require('path');
let router=require('koa-router')();
// 1、解决正确获得控制器文件夹路径
function foreachRouter(dir) {
    let files = fs.readdirSync(dir);
    let controllerFiles = files.filter((name) => {
        return name.endsWith('.js') && name !== 'index.js';
        
    });

    return controllerFiles;


}

function registRouter(files) {

    files.forEach(item => {
        let tmpFile = path.join(__dirname, item);
        let tmpRoutes = require(tmpFile);
        for (var x in tmpRoutes) {
            console.log(x);
            // 获得键值对中的值，里面的请求类型
            let type = tmpRoutes[x][0];
            // 获取键值中的值（是一个数组），里面的处理函数
            let fn = tmpRoutes[x][1];
            if (type === 'get') {
                router.get(x, fn);
            }
            else if (type === 'post') {
                router.post(x, fn);
            }
            else if (type === 'put') {
                router.put(x, fn);
            }
            else if (type === 'delete') {
                router.post(x, fn);
            }

        }
    })

}
module.exports= function(){

    let dir = __dirname;
    let controllerFiles = foreachRouter(dir)
    registRouter(controllerFiles);
    return router.routes();

}
